//
//  NSBundle+Localization.m
//  Localization
//
//  Created by han on 2019/1/25.
//  Copyright © 2019 han. All rights reserved.
//

#import "NSBundle+Localization.h"

@implementation NSBundle (Localization)

+ (instancetype)localizationBundle {
    static NSBundle *localizationBundle = nil;
    if (localizationBundle == nil) {
        // 这里不使用mainBundle是为了适配pod
        NSBundle *bundle = [NSBundle mainBundle];
//        NSBundle *bundle = [NSBundle bundleForClass:[TableViewController class]];
        localizationBundle = [NSBundle bundleWithPath:[bundle pathForResource:@"LocalizationResource" ofType:@"bundle"]];
    }
    return localizationBundle;
}

+ (NSString *)localizedStringForKey:(NSString *)key {
  return  [self localizedStringForKey:key value:nil];
}
+ (NSString *)localizedStringForKey:(NSString *)key value:(nullable NSString *)value {
    static NSBundle *bundle = nil;
    if (bundle == nil) {
        // （iOS获取的语言字符串比较不稳定）目前框架只处理en、zh-Hans、zh-Hant三种情况，其他按照系统默认处理
        NSString *language = [NSLocale preferredLanguages].firstObject;
        if ([language hasPrefix:@"en"]) {
            language = @"en";
        } else if ([language hasPrefix:@"zh"]) {
            if ([language rangeOfString:@"Hans"].location != NSNotFound) {
                language = @"zh-Hans"; // 简体中文
            }
            else { // zh-Hant\zh-HK\zh-TW
//                language = @"zh-Hant"; // 繁體中文
                language = @"en";// 当前项目没有处理繁体中文，默认英文
            }
        } else {
            language = @"en";
        }
        
        // 从bundle中查找资源
        bundle = [NSBundle bundleWithPath:[[NSBundle localizationBundle] pathForResource:language ofType:@"lproj"]];
    }
    value = [bundle localizedStringForKey:key value:value table:nil];
    return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
}

+ (UIImage *)bundleImageWithName:(NSString *)imageName ofType:(NSString *)ext{
    return [UIImage imageWithContentsOfFile:[[self localizationBundle] pathForResource:imageName ofType:ext]] ;
}
+ (UIImage *)localizedImageWithName:(NSString *)imageName ofType:(NSString *)ext {
    return [self bundleImageWithName:[self localizedStringForKey:imageName] ofType:ext];
}


@end
